import { SearchDto } from '@/common/dto/base-search.dto';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateDictDataDto } from './dto/create-dict-data.dto';
import { UpdateDictDatumDto } from './dto/update-dict-data.dto';
import { SysDictData } from './entities/dicts-data.entity';
import { IdsDto } from '@/common/dto/ids.dto';

@Injectable()
export class DictDataService {
  constructor(
    @InjectRepository(SysDictData)
    private dictDataRepository: Repository<SysDictData>,
  ) {}
  create(dictCode: string, createDictDataDto: CreateDictDataDto) {
    createDictDataDto.dictCode = createDictDataDto.dictCode || dictCode;
    return this.dictDataRepository.save(createDictDataDto);
  }

  async findAll(dictCode: string, query: SearchDto) {
    const page = query.pageNum || 1;
    const limit = query.pageSize || 10;

    const [data, count] = await this.dictDataRepository.findAndCount({
      where: {
        dictCode,
      },
      skip: (page - 1) * limit,
      take: limit,
    });
    return {
      list: data,
      total: count,
    };
  }

  async findList(dictCode: string) {
    const list = await this.dictDataRepository.find({
      where: {
        dictCode,
      },
    });
    return list.map((item) => {
      return {
        label: item.label,
        value: item.value,
        tagType: item.tagType,
      };
    });
  }

  findOne(params: { dictCode: string; id: string }) {
    return this.dictDataRepository.findOne({
      where: {
        dictCode: params.dictCode,
        id: params.id,
      },
    });
  }

  update(
    params: { dictCode: string; id: string },
    updateDictDatumDto: UpdateDictDatumDto,
  ) {
    updateDictDatumDto.dictCode = params.dictCode;
    return this.dictDataRepository.update(params.id, updateDictDatumDto);
  }

  remove(params: IdsDto) {
    const ids = params.ids.split(',');
    return this.dictDataRepository.delete(ids);
  }
}
